package drds.plus.executor.cursor.cursor.impl.common;

import drds.plus.executor.cursor.cursor.IAffectRowCursor;
import drds.plus.executor.cursor.cursor.impl.SortingCursor;
import drds.plus.executor.cursor.cursor.impl.result_cursor.ResultCursor;
import drds.plus.executor.cursor.cursor_metadata.Column;
import drds.plus.executor.cursor.cursor_metadata.CursorMetaData;
import drds.plus.executor.cursor.cursor_metadata.CursorMetaDataImpl;
import drds.plus.executor.row_values.ArrayRowValues;
import drds.plus.executor.row_values.RowValues;
import drds.plus.executor.utils.Utils;
import drds.plus.sql_process.type.Type;
import drds.plus.util.GeneralUtil;

import java.util.Arrays;

public class AffectRowCursor extends SortingCursor implements IAffectRowCursor {

    protected boolean first = true;
    protected CursorMetaData cursorMetaData;
    private int affectRow = 0;
    private boolean schemaInited = false;

    public AffectRowCursor(int affectRow) {
        super(null, null, null);
        this.affectRow = affectRow;
    }

    protected CursorMetaData initSchema() {
        if (schemaInited) {
            return cursorMetaData;
        }
        schemaInited = true;
        Column column = new Column(ResultCursor.AFFECT_ROW, Type.IntegerType);
        CursorMetaDataImpl cursorMetaData = CursorMetaDataImpl.buildCursorMetaData("", Arrays.asList(column), 1);
        this.cursorMetaData = cursorMetaData;
        return cursorMetaData;
    }

    public RowValues next() throws RuntimeException {
        initSchema();
        if (!first) {
            return null;
        }
        first = false;
        ArrayRowValues arrayRowSet = new ArrayRowValues(1, cursorMetaData);
        arrayRowSet.setInteger(0, affectRow);
        return arrayRowSet;
    }

    public String toStringWithInden(int inden) {
        StringBuilder sb = new StringBuilder();
        String tab = GeneralUtil.getTab(inden);
        sb.append(tab).append("【AffectRowCursor : ").append("\n");
        Utils.printCursorMetaData(cursorMetaData, inden, sb);
        Utils.printOrderByList(orderByList, inden, sb);
        sb.append(super.toStringWithInden(inden + 1));
        return sb.toString();
    }

    public String toString() {
        return toStringWithInden(0);
    }

}
